package importExport;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintStream;
import java.util.Hashtable;
import java.util.Vector;



public class CsvParser {

	public static Vector readFile(File cFile, String separator) {

		Vector<String[]> stringVector = new Vector<String[]>();
		if (cFile != null) {
			try {
				BufferedReader in = new BufferedReader(new FileReader(cFile));
				String readString;
				while ((readString = in.readLine()) != null) {
					stringVector.add(readString.split(separator));
				}
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return stringVector;
	}
	public static Vector<Hashtable> readFileAsHashTableList(File cFile, String separator) {
		Vector cVec=readFile(cFile, separator);
		Vector <Hashtable> rows=new Vector <Hashtable>();
		String[] labels=(String[]) cVec.get(0);
		System.out.println(labels.length);
		for (int i=1;i<cVec.size();i++){ 
			Hashtable<String, String> row=new Hashtable<String, String>();
			String[] data=(String[]) cVec.get(i);
			System.out.println(data.length);
			for (int j=0;j<data.length;j++){
				row.put(labels[j],data[j]);
			}
			rows.add(row);
		}
		return rows;
	}
	public static void writeCSV(File cFile,Vector stringArrays,String separator){
		FileOutputStream out;
		try {
			out = new FileOutputStream(cFile);
			PrintStream p = new PrintStream(out);
			for (int i=0;i<stringArrays.size();i++){
				String[] valueLine=(String[])stringArrays.get(i);
				for (int j=0;j<valueLine.length-1;j++){
					p.print(valueLine[j]);
					p.print(separator);
				}
				p.println(valueLine[valueLine.length-1]);
			}
		} catch (Exception e) {
			System.err.println("error writing file");
		}
	}
}
